package com.fsxgt.datagrid.component.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.concurrent.ExecutionException;

import org.apache.ibatis.executor.ExecutorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson2.JSONObject;
import com.fsxgt.datagrid.component.bo.CmpFetchDataBO;
import com.fsxgt.datagrid.component.service.impl.CmpFetchDataService;
import com.fsxgt.datagrid.core.exception.DataGridException;
import com.fsxgt.datagrid.core.utils.ReturnT;
import com.fsxgt.datagrid.ds.bo.DatasourceJdbcBO;
import com.fsxgt.datagrid.ds.service.impl.DatasourceJdbcService;
import com.fsxgt.datagrid.ds.service.impl.MetaService;
import com.fsxgt.datagrid.flow.exception.FlowException;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "数据抓取接口", value = "FetchDataController")
@RequestMapping(produces = "application/json; charset=UTF-8",path = "/fetchData")
@RestController
public class FetchDataController extends BaseController {

	@Autowired
	private DatasourceJdbcService datasourceJdbcService;
	@Autowired
	private CmpFetchDataService cmpFetchDataService;
	
	
	@Autowired
	private MetaService metaService;
 

	
	
	@ApiOperation(hidden = true, value = "查找字段", notes = "")
	@RequestMapping(path = "/findColumns", method = RequestMethod.POST)
	public ReturnT findColumns(@RequestBody JSONObject param) throws Exception {
		
		DatasourceJdbcBO bo = datasourceJdbcService.getDatasourceById(Long.valueOf(param.getString("datasourceId")));
		
		return new ReturnT(metaService.findColumnNamesForSql(bo, param.getString("sqlText")));

	}
	
	@ApiOperation(hidden = true, value = "保存", notes = "")
	@RequestMapping(path = "/saveFetchData", method = RequestMethod.POST)
	public ReturnT saveFetchData(@RequestBody CmpFetchDataBO bo) throws DataGridException, IOException, ExecutorException, NumberFormatException, ExecutionException, SQLException, FlowException {
		
		cmpFetchDataService.saveCmpFetchData(bo);
		
		return new ReturnT();

	}
	
	@ApiOperation(hidden = true, value = "获取组件", notes = "")
	@RequestMapping(path = "/getFetchData", method = RequestMethod.POST)
	public ReturnT getFetchData(@RequestBody CmpFetchDataBO cmpFetchDataBO) throws DataGridException, IOException, ExecutorException, NumberFormatException, ExecutionException {
		
		CmpFetchDataBO bo = cmpFetchDataService.getFetchData(cmpFetchDataBO);
		
		return new ReturnT(bo);

	}
	
	
	
	
	


	

}